package com.lhkk.inventoryvehicle.camera

import java.util.concurrent.ExecutorService
import java.util.concurrent.Executors
import java.util.concurrent.LinkedBlockingQueue
import java.util.concurrent.ThreadPoolExecutor
import java.util.concurrent.TimeUnit

/**
 * 程池单例
 */
class ThreadPoolInstance {

    companion object {
        private var INSTANCE: ThreadPoolInstance? = null
        private var singleThreadExecutor: ExecutorService? = null
        private var fixedThreadPool: ExecutorService? = null
        private var threadPoolExecutor: ThreadPoolExecutor? = null

        fun getInstance(): ThreadPoolInstance? {
            synchronized(ThreadPoolInstance::class.java) {
                if (INSTANCE == null) {
                    INSTANCE = ThreadPoolInstance()
                }
            }
            return INSTANCE
        }
    }

    /**
     * 获取基本线程池
     * keepAliveTime设置为0，非核心线程空闲时会被立即回收
     */
    fun getThreadPoolExecutor(): ThreadPoolExecutor? {
        synchronized(ThreadPoolInstance::class.java) {
            if (threadPoolExecutor == null) {
                threadPoolExecutor = ThreadPoolExecutor(
                        5, 10, 0, TimeUnit.SECONDS,
                        LinkedBlockingQueue(Int.MAX_VALUE)
                )
            }
        }
        return threadPoolExecutor
    }

    /**
     * 获取单线程池
     */
    fun getSingleThreadExecutor(): ExecutorService? {
        synchronized(ThreadPoolInstance::class.java) {
            if (singleThreadExecutor == null) {
                singleThreadExecutor = Executors.newSingleThreadExecutor()
            }
        }
        return singleThreadExecutor
    }

    /**
     * 获取固定核心数线程池
     */
    fun getFixedThreadPool(): ExecutorService? {
        synchronized(ThreadPoolInstance::class.java) {
            if (fixedThreadPool == null) {
                fixedThreadPool = Executors.newFixedThreadPool(5)
            }
        }
        return fixedThreadPool
    }
}